package com.bawei.module_open.module

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.SurfaceTexture
import android.hardware.Camera
import android.media.MediaRecorder
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Surface
import android.view.TextureView
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.module_open.R
import java.io.File

/**
 * 视频录制页面
 * 集成七牛云短视频 SDK 的录制和编辑功能
 */
@Route(path = "/open/VideoRecordingActivity")
class VideoRecordingActivity : AppCompatActivity(), VideoRecordCallback, VideoEditCallback {
    
    companion object {
        private const val TAG = "VideoRecordingActivity"
        private const val REQUEST_PERMISSIONS = 100
        private const val QINIU_LICENSE_KEY = "InISKTYqgmlhPCAiiirUVfxHMHgS8hNFrGkKqcOP" // 替换为你的七牛云授权密钥
        private val REQUIRED_PERMISSIONS = arrayOf(
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
        )
    }
    
    private var camera: Camera? = null
    private var textureView: TextureView? = null
    private var isRecording = false
    private var currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK
    private var mediaRecorder: MediaRecorder? = null
    private var videoFile: File? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video_recording)
        
        // 初始化视图
        initViews()
        
        // 检查权限
        if (checkAndRequestAllPermissions()) {
            initVideoRecording()
        }
    }
    
    /**
     * 初始化视图
     */
    private fun initViews() {
        textureView = findViewById(R.id.preview_container)
        textureView?.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
            override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
                startCameraPreview()
            }
            
            override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {}
            
            override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
                return true
            }
            
            override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {}
        }
        
        // 设置按钮点击事件
        findViewById<ImageView>(R.id.btn_back).setOnClickListener {
            finish()
        }
        
        findViewById<ImageView>(R.id.btn_record).setOnClickListener {
            if (isRecording) {
                stopRecording()
            } else {
                startRecording()
            }
        }
        
        findViewById<ImageView>(R.id.btn_switch_camera).setOnClickListener {
            switchCamera()
        }
    }
    
    /**
     * 启动相机预览
     */
    private fun startCameraPreview() {
        try {
            // 释放之前的摄像头
            camera?.stopPreview()
            camera?.release()
            
            camera = Camera.open(currentCameraId)
            
            // 设置预览方向
            camera?.setDisplayOrientation(90)
            
            // 设置预览尺寸
            val parameters = camera?.parameters
            val previewSizes = parameters?.supportedPreviewSizes
            if (previewSizes != null && previewSizes.isNotEmpty()) {
                // 选择合适的分辨率
                val targetSize = previewSizes.find { it.width >= 720 && it.height >= 1280 }
                    ?: previewSizes[0]
                parameters.setPreviewSize(targetSize.width, targetSize.height)
                camera?.parameters = parameters
            }
            
            camera?.setPreviewTexture(textureView?.surfaceTexture)
            camera?.startPreview()
        } catch (e: Exception) {
            Toast.makeText(this, "相机启动失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 切换摄像头
     */
    private fun switchCamera() {
        if (isRecording) {
            Toast.makeText(this, "录制中无法切换摄像头", Toast.LENGTH_SHORT).show()
            return
        }
        
        currentCameraId = if (currentCameraId == Camera.CameraInfo.CAMERA_FACING_BACK) {
            Camera.CameraInfo.CAMERA_FACING_FRONT
        } else {
            Camera.CameraInfo.CAMERA_FACING_BACK
        }
        
        startCameraPreview()
    }
    
    /**
     * 初始化视频录制功能
     */
    private fun initVideoRecording() {
        try {
            // 检查设备能力
            MediaRecorderHelper.checkDeviceCapabilities(this)
            
            // 初始化七牛云短视频 SDK
            QiniuVideoManager.init(this, QINIU_LICENSE_KEY)
        } catch (e: Exception) {
            Toast.makeText(this, "初始化失败: ${e.message}", Toast.LENGTH_SHORT).show()
            finish()
        }
    }
    
    /**
     * 开始录制
     */
    private fun startRecording() {
        if (isRecording) return
        
        try {
            // 检查七牛云 SDK 是否可用
            if (QiniuVideoManager.isInitialized()) {
                // 使用七牛云 SDK 录制
                startQiniuRecording()
            } else {
                // 使用原生录制作为备选
                startNativeRecording()
            }
        } catch (e: Exception) {
            Log.e(TAG, "Failed to start recording", e)
            Toast.makeText(this, "录制失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 使用七牛云 SDK 录制
     */
    private fun startQiniuRecording() {
        val config = VideoRecordConfig(
            videoWidth = 720,
            videoHeight = 1280,
            frameRate = 30,
            bitrate = 2000000,
            maxDuration = 60000,
            minDuration = 3000
        )

        QiniuVideoManager.startRecording(this, config, object : VideoRecordCallback {
            override fun onRecordSuccess(videoPath: String) {
                runOnUiThread {
                    isRecording = false
                    updateRecordingUI()
                    Toast.makeText(this@VideoRecordingActivity, "录制完成", Toast.LENGTH_SHORT)
                        .show()

//                    // 跳转到编辑页面
                    startVideoEdit(videoPath)
                }
            }

            override fun onRecordCancel() {
                runOnUiThread {
                    isRecording = false
                    updateRecordingUI()
                    Toast.makeText(this@VideoRecordingActivity, "录制已取消", Toast.LENGTH_SHORT)
                        .show()
                }
            }

            override fun onError(error: String) {
                runOnUiThread {
                    isRecording = false
                    updateRecordingUI()
                    Toast.makeText(
                        this@VideoRecordingActivity,
                        "录制失败: $error",
                        Toast.LENGTH_SHORT
                    ).show()

                    // 如果七牛云录制失败，尝试使用原生录制
                    Log.w(TAG, "Qiniu recording failed, trying native recording")
                    startNativeRecording()
                }
            }
        })
    }
    
    /**
     * 使用原生录制
     */
    private fun startNativeRecording() {
        if (isRecording) return
        
        try {
            // 创建视频文件
            val outputDir = File(getExternalFilesDir(null), "videos")
            if (!outputDir.exists()) {
                outputDir.mkdirs()
            }
            
            videoFile = File(outputDir, "video_${System.currentTimeMillis()}.mp4")
            
            // 使用辅助类创建安全的 MediaRecorder
            mediaRecorder =
                MediaRecorderHelper.createSafeMediaRecorder(videoFile?.absolutePath ?: "")
            
            if (mediaRecorder == null) {
                Toast.makeText(this, "创建录制器失败", Toast.LENGTH_SHORT).show()
                return
            }
            
            // 设置预览显示
            mediaRecorder?.setPreviewDisplay(Surface(textureView?.surfaceTexture))
            
            // 设置方向
            try {
                mediaRecorder?.setOrientationHint(90)
            } catch (e: Exception) {
                // 如果设置失败，忽略
            }
            
            // 准备录制
            mediaRecorder?.prepare()
            
            // 开始录制
            mediaRecorder?.start()
            
            isRecording = true
            updateRecordingUI()
            
            Toast.makeText(this, "开始录制", Toast.LENGTH_SHORT).show()
            
        } catch (e: Exception) {
            val errorMessage = MediaRecorderHelper.getErrorMessage(e.message ?: "")
            Toast.makeText(this, "录制失败: $errorMessage", Toast.LENGTH_LONG).show()
            
            // 清理资源
            try {
                mediaRecorder?.release()
            } catch (releaseException: Exception) {
                // 忽略释放异常
            }
            mediaRecorder = null
            isRecording = false
        }
    }
    
    /**
     * 停止录制
     */
    private fun stopRecording() {
        if (!isRecording) return
        
        try {
            // 停止录制
            mediaRecorder?.stop()
            
            // 释放资源
            mediaRecorder?.release()
            mediaRecorder = null
            
            isRecording = false
            updateRecordingUI()
            
            Toast.makeText(this, "录制完成", Toast.LENGTH_SHORT).show()
            
            // 检查录制文件是否有效
            videoFile?.let { file ->
                if (MediaRecorderHelper.isVideoFileValid(file.absolutePath)) {
                    startVideoEdit(file.absolutePath)
                } else {
                    Toast.makeText(this, "录制文件无效，请重试", Toast.LENGTH_SHORT).show()
                }
            }
            
        } catch (e: Exception) {
            Toast.makeText(this, "停止录制失败: ${e.message}", Toast.LENGTH_SHORT).show()
            
            // 清理资源
            try {
                mediaRecorder?.release()
            } catch (releaseException: Exception) {
                // 忽略释放异常
            }
            mediaRecorder = null
            isRecording = false
        }
    }
    
    /**
     * 更新录制界面UI
     */
    private fun updateRecordingUI() {
        runOnUiThread {
            if (isRecording) {
                findViewById<TextView>(R.id.recording_indicator).visibility = View.VISIBLE
                findViewById<ImageView>(R.id.btn_record).setImageResource(R.drawable.ic_stop)
            } else {
                findViewById<TextView>(R.id.recording_indicator).visibility = View.GONE
                findViewById<ImageView>(R.id.btn_record).setImageResource(R.drawable.ic_record)
            }
        }
    }
    
    /**
     * 启动视频编辑
     */
    private fun startVideoEdit(videoPath: String) {
        val intent = Intent(this, com.bawei.module_open.module.VideoEditActivity::class.java)
        intent.putExtra("video_path", videoPath)
        startActivity(intent)
        finish() // 录制完成后关闭录制页面
    }
    
    /**
     * 检查并动态申请所有必要权限，兼容Android 11+
     */
    // VideoRecordCallback 实现
    override fun onRecordSuccess(videoPath: String) {
        runOnUiThread {
            Toast.makeText(this, "录制成功，开始编辑", Toast.LENGTH_SHORT).show()
            startVideoEdit(videoPath) // 改这里
        }
    }
    private fun checkAndRequestAllPermissions(): Boolean {
        val permissions = mutableListOf(
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO
        )
        // 只有 Android 10 及以下才需要动态申请存储权限
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) {
            permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
        }
        val notGranted = permissions.filter {
            ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }
        if (notGranted.isNotEmpty()) {
            ActivityCompat.requestPermissions(this, notGranted.toTypedArray(), REQUEST_PERMISSIONS)
            return false
        }
        return true
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_PERMISSIONS) {
            // 只要必要权限都授权了就初始化
            if (grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
                initVideoRecording()
            } else {
                Toast.makeText(this, "需要相机和录音权限才能录制视频，请全部授权！", Toast.LENGTH_LONG).show()
            }
        }
    }


    override fun onRecordCancel() {
        runOnUiThread {
            Toast.makeText(this, "录制已取消", Toast.LENGTH_SHORT).show()
            finish()
        }
    }
    
    override fun onError(error: String) {
        runOnUiThread {
            Toast.makeText(this, "录制失败: $error", Toast.LENGTH_SHORT).show()
            finish()
        }
    }
    
    // VideoEditCallback 实现
    override fun onEditSuccess(outputPath: String) {
        runOnUiThread {
            Toast.makeText(this, "视频编辑完成", Toast.LENGTH_SHORT).show()
            finish()
        }
    }
    
    override fun onEditCancel() {
        runOnUiThread {
            Toast.makeText(this, "编辑已取消", Toast.LENGTH_SHORT).show()
            finish()
        }
    }
    
    override fun onSaveDraft() {
        runOnUiThread {
            Toast.makeText(this, "草稿已保存", Toast.LENGTH_SHORT).show()
            finish()
        }
    }

    
    override fun onPause() {
        super.onPause()
        if (isRecording) {
            stopRecording()
        }
        camera?.stopPreview()
        camera?.release()
        camera = null
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 释放七牛云 SDK 资源
        QiniuVideoManager.release()
    }
} 